<?php
class NewProjectForm extends CFormModel {

	const STEP_OWNER = 1;
	const STEP_PROJECT = 2;
	const STEP_TOPICS = 3;

	// -- Owner specific fields
	public $first_name;
	public $last_name;
	public $gender;
	public $birth_date;
	public $address1;
	public $address2;
	public $address3;
	public $city_id;
	public $phone_number;
	public $email;
	public $referent;
	public $service_id;
	public $adviser_initials;
	public $owner_id;
	public $specificData = array ();
	
	// -- Project specific fields
	public $project_id;
	public $activity;
	public $description;
	public $route_mnemonic;

	// -- Selected topics - validation and comments
	public $topics = array ();
	public $starts = array ();
	public $ends = array ();
	public $owner = array ();
	public $adviser = array ();
	public $validation_comment = array ();
	public $objective = array ();
	public $objective_needs = array ();
	public $objective_contacts = array ();
	public $adviser_validation = array ();
	public $owner_validation = array ();

	// -- Current step
	public $form_type = self::STEP_OWNER;

	public function __construct() {
		$specificData = Yii::app()->parameter->getParametersArray('OWNER_SPEC');
		$this->adviser_initials = Yii::app()->user->getState('dbuser')->initials;
		foreach ($specificData as $id=>$specificDatum) {
			$this->specificData[$id] = ""; 
		}
	}

	public function rules() {
		return array (
			array (
				'first_name',
				'length',
				'max' => 100
			),
			array (
				'last_name',
				'length',
				'max' => 100
			),
			array (
				'gender',
				'length',
				'max' => 5
			),
			array (
				'address1',
				'length',
				'max' => 255
			),
			array (
				'address2',
				'length',
				'max' => 255
			),
			array (
				'address3',
				'length',
				'max' => 255
			),
			array (
				'phone_number',
				'length',
				'max' => 255
			),
			array (
				'email',
				'length',
				'max' => 255
			),
			array (
				'referent',
				'length',
				'max' => 255
			),
			array (
				'email',
				'application.extensions.emailvalidator.EEmailValidator',
				'strictValidation' => false
			),
			array (
				'activity',
				'length',
				'max' => 255
			),
			array (
				'route_mnemonic',
				'length',
				'max' => 5
			),


		);
	}

	private static $owner_fields = array (
		'owner_id',
		'first_name',
		'last_name',
		'gender',
		'birth_date',
		'address1',
		'address2',
		'address3',
		'city_id',
		'email',
		'phone_number',
		'referent',
		'service_id',
		'adviser_initials',
		'specificData'
	);

	private static $project_fields = array (
		'project_id',
		'activity',
		'description',
		'route_mnemonic'
	);

	private static $topics_fields = array (
		'topics'
	);

	public function attributeLabels() {
		return array (
			'form_type' => Yii::t('database', 'Step'),

			'owner_id' => Yii::t('database', 'Owner'),
			'first_name' => Yii::t('database', 'First Name'),
			'last_name' => Yii::t('database', 'Last Name'),
			'gender' => Yii::t('database', 'Gender'),
			'birth_date' => Yii::t('database', 'Birth Date'),
			'address1' => Yii::t('database', 'Address1'),
			'address2' => Yii::t('database', 'Address2'),
			'address3' => Yii::t('database', 'Address3'),
			'city_id' => Yii::t('database', 'City'),
			'phone_number' => Yii::t('database', 'Phone Number'),
			'email' => Yii::t('database', 'Email'),
			'referent' => Yii::t('database', 'Referent'),
			'service_id' => Yii::t('database', 'Service'),
			'adviser_initials' => Yii::t('database', 'Adviser Initials'),
			'specificData' => Yii::t('database', 'Specific Data'),
		
			'project_id' => Yii::t('database', 'Project'),
			'activity' => Yii::t('database', 'Activity'),
			'description' => Yii::t('database', 'Description'),
			'route_mnemonic' => Yii::t('database', 'Route'),


		);
	}

	public function getHiddenFields() {
		if ($this->form_type == self::STEP_OWNER)
			return array_diff(array_keys($this->attributeLabels()), self::$owner_fields);
		else
			if ($this->form_type == self::STEP_PROJECT)
				return array_diff(array_keys($this->attributeLabels()), self::$project_fields);
			else
				if ($this->form_type == self::STEP_TOPICS)
					return array_diff(array_keys($this->attributeLabels()), self::$topics_fields);

		return array ();
	}

	public function checkOwner() {
		$this->checkNotEmpty('first_name');
		$this->checkNotEmpty('referent');
		$this->checkNotEmpty('birth_date');
		$this->checkNotEmpty('city_id');
	}

	public function checkProject() {
		$this->checkNotEmpty('activity');
		$this->checkNotEmpty('route_mnemonic');
	}

	public function checkTopics() {
		if ($this->topics == null || !is_array($this->topics) || count($this->topics) <= 0)
			$this->addError('topics', Yii::t('project', 'Please select at least one topic'));
	}

	protected function checkNotEmpty($attribute) {
		if ($this->isEmpty($this-> $attribute)) {
			$this->addRequiredError($attribute);
		}
	}

	protected function addRequiredError($attribute) {
		$label = $this->attributeLabels();
		$label = $label[$attribute];
		$message = Yii::t('yii', '{attribute} cannot be blank.', array (
			'{attribute}' => $label
		));
		$this->addError($attribute, $message);
	}

	public function isEmpty($value, $trim = false) {
		return $value === null || $value === array () || $value === '' || $trim && !is_array($value) && trim($value) === '';
	}

	public function isAttributeRequired($attribute, $scenario = '') {
		if ($attribute == 'first_name' || $attribute == 'referent' || $attribute == 'birth_date' || $attribute == 'city_id')
			return true;
		else
			if ($attribute == 'activity' || $attribute == 'route_mnemonic')
				return true;
			else
				return parent::isAttributeRequired($attribute, $scenario);
	}

	public function saveAll() {
		$transaction = Yii::app()->db->beginTransaction();
		$project = null;
		$meeting = null;

		{
			$this->adviser_initials = Yii::app()->user->getState('dbuser')->initials;
			$owner = null;
			if (!$this->isEmpty($this->owner_id)) {
				$owner = Owner::model()->findByPk($this->owner_id);
			}
			if ($owner == null) {
				$owner = new Owner();
			}
			$owner->attributes = $this->attributes;
			$owner->birth_date = Constants::toSqlDate($this->birth_date);

			if (!$owner->save()) {
				$this->addError('owner_id', Yii::t('project', 'Unable to save owner'));
				$this->addErrors($owner->getErrors());
			}
			
			$specificData = Yii::app()->parameter->getParametersArray('OWNER_SPEC');
			foreach ($this->specificData as $id => $specificDatum)
			{
				$o = new OwnerSpecificData();
				$o->owner_id = $owner->id;
				$o->field_name = $specificData[$id]['FLDNAM'];
				$o->field_value = $specificDatum;
				$o->save();
			}
		}

		if (!$this->isEmpty($owner->id)) {
			if (!$this->isEmpty($this->project_id)) {
				$owner = Project::model()->findByPk($this->project_id);
			}
			if ($project == null) {
				$project = new Project();
			}
			$project->attributes = $this->attributes;
			$project->owner_id = $owner->id;

			if (!$project->save()) {
				$this->addError('project_id', Yii::t('project', 'Unable to save project'));
				$this->addErrors($project->getErrors());
			}
		}

		if (!$this->isEmpty($project->id)) {
			if ($project->meetings != null && count($project->meetings) > 0) {
				$meeting = $project->meetings[0];
			} else {
				$meeting = new Meetings();
				$meeting->project_id = $project->id;
				$meeting->meeting_date = date(Constants::SQL_DATE_FORMAT);
				if (!$meeting->save()){
					$this->addErrors($meetings->getErrors());
				}
			}

			foreach ($this->topics as $topic => $n) {
				$t = Topic::model()->findByAttributes(array (
					'id' => $topic
				));
				$ptopic = $this->createProjectTopic($meeting, $project, $topic);
				$ptopic->weeks_number = $this->weeks[$topic];
				if (!$ptopic->save()) {
					$this->addError('topics_' . $topic, Yii::t('project', '#{topic_id}: &#171;{topic_label}&#187;: Unable to save topic ', array (
						"{topic_id}" => $topic,
						"{topic_label}" => $t->label
					)));
					$this->convertErrors($topic, $ptopic->getErrors());
				}
				$ptopic = ProjectTopic::model()->findByPk($ptopic->id);
				$this->topics[$topic] = $ptopic;
			}

			// For each adviser_validation_topic, we update the topic
			foreach ($this->adviser_validation as $id => $adviser_validation) {
				if ($adviser_validation != "" //
				&& isset ($this->topics[$adviser_validation]) //
				&& isset ($this->topics[$id])) {
					$this->topics[$id]->adviser_validation_project_topic = $this->topics[$adviser_validation];
					$this->topics[$id]->adviser_validation_topic = $this->topics[$adviser_validation]->id;
					if (!$this->topics[$id]->save()) {
						$this->addError('topics_' . $topic, Yii::t('project', '#{topic_id}: Unable to set adviser validation on topic', array (
							'{topic_id}' => $topic
						)));
						$this->convertErrors($topic, $ptopic->getErrors());
					}
				}
			}

			// For each adviser_validation_topic, we update the topic
			foreach ($this->owner_validation as $id => $owner_validation) {
				if ($owner_validation != "" //
				&& isset ($this->topics[$owner_validation]) //
				&& isset ($this->topics[$id])) {
					$this->topics[$id]->owner_validation_project_topic = $this->topics[$owner_validation];
					$this->topics[$id]->owner_validation_topic = $this->topics[$owner_validation]->id;
					if (!$this->topics[$id]->save()) {
						$this->addError('topics_' . $topic, Yii::t('project', '#{topic_id}: Unable to set owner validation on topic', array (
							'{topic_id}' => $topic
						)));
						$this->convertErrors($topic, $ptopic->getErrors());
					}
				}
			}
		}

		if ($this->hasErrors()) {
			$transaction->rollBack();
		} else {
			$this->owner_id = $owner->id;
			$this->project_id = $project->id;
			$transaction->commit();
		}

	}
	protected function createProjectTopic($meeting, $project, $topic_id) {
		$ptopic = ProjectTopic::model()->findByAttributes(array (
			'project_id' => $project->id,
			'topic_id' => $topic_id
		));
		if ($ptopic == null) {
			$ptopic = new ProjectTopic();
			$ptopic->input_date = date(Constants::SQL_DATE_FORMAT);
			$ptopic->project_id = $project->id;
			$ptopic->topic_id = $topic_id;
		}
		$ptopic->adviser_validation = (isset ($this->adviser[$topic_id]) && $this->adviser[$topic_id] == true ? Constants::TRUE : Constants::FALSE);
		if ($ptopic->adviser_validation == Constants::TRUE) {
			if ($ptopic->adviser_validation_date == null || $ptopic->adviser_validation_date == "")
				$ptopic->adviser_validation_date = $meeting->meeting_date;
		} else {
			$ptopic->adviser_validation_date = null;
		}

		$ptopic->owner_validation = (isset ($this->owner[$topic_id]) && $this->owner[$topic_id] == true ? Constants::TRUE : Constants::FALSE);
		if ($ptopic->owner_validation == Constants::TRUE) {
			if ($ptopic->owner_validation_date == null || $ptopic->owner_validation_date == '')
				$ptopic->owner_validation_date = $meeting->meeting_date;
		} else {
			$ptopic->owner_validation_date = null;
		}
		$ptopic->validation_comments = (isset ($this->comment[$topic_id]) ? $this->comment[$topic_id] : "");
		$ptopic->objective = Constants::FALSE;
		$ptopic->adviser_validation_topic = null;
		$ptopic->owner_validation_topic = null;

		return $ptopic;
	}

	protected function convertErrors($id, $errors) {
		$err = array ();
		if (is_array($errors)) {
			foreach ($errors as $name => $error) {
				if (is_array($error)) {
					foreach ($error as $e)
						$err[$name .
						'_' . $id][] = '#' . $id . ': ' . $e;
				} else {
					$err[$name . '_' . $id][] = '#' . $id . ': ' . $error;
				}
			}
		}
		$this->addErrors($err);
	}
}
?>
